<?php
if (!defined('IN_IPB')) exit("<h1>Incorrect access</h1> You may not access this file without the acp.");

class ibstore_converter
{
	var $ipsclass;
	var $convert_LIMIT = 500;
	var $FILENAME_CONVERT = array(
									'bank/item_autocollect' => '',
									'bank/item_increaseinterest' => 'bank/item_increase_own_interest.php',
									
									'otherusers/item_changeotherestitle' => 'other/item_changeothertitle.php',
									'otherusers/item_decreaseothereinterest' => 'bank/item_decrease_other_interest.php',
									'otherusers/item_otherssignaturechange' => 'other/item_othersignature.php',
									'otherusers/item_temporaryban' => 'other/item_temporaryban.php',
									'otherusers/item_unbanuser' => 'other/item_unbanmember.php',
									'otherusers/item_uploadotheresavatar' => 'other/item_changeotheravatar.php',
									'otherusers/item_viewotherwarn' => 'other/item_viewwarning.php',
									
									'ownchange/item_addgalleryavatar' => 'own/item_galleryavatar.php',
									'ownchange/item_addtopost' => 'own/item_addtopost.php',
									'ownchange/item_bypassflood' => 'own/item_bypassflood.php',
									'ownchange/item_changegroup' => 'own/item_changegroup.php',
									'ownchange/item_changename' => 'own/item_changeloginname.php',
									'ownchange/item_changeyourtitle' => 'own/item_changeowntitle.php',
									'ownchange/item_messagetouser' => 'own/item_secretmessage.php',
									'ownchange/item_nameeffect' => 'own/item_nameeffect.php',
									'ownchange/item_paytodownload' => '',
									'ownchange/item_uploadavatar' => 'own/item_uploadavatar.php',
									
									'ownpoints/item_mysterybox' => 'random/item_randomitem.php',
									'ownpoints/item_mysterything' => 'random/mystery.php',
									'ownpoints/item_randommoney' => 'random/item_randommoney.php',
									
									'steal/item_banksteal' => '',
									'steal/item_basicsteal' => 'steal/item_basicsteal.php',
									
									'topic/item_closeopenowntopic' => 'topic/item_openclosetopic.php',
									'topic/item_opencloseanytopic' => 'topic/item_openclosetopic.php',
									'topic/item_pinunpinanytopic' => 'topic/item_pintopic.php',
									'topic/item_pinunpinowntopic' => 'topic/item_pintopic.php',
									
									'upload/item_uploademoticon' => '/item_uploademotion.php',
									
									'item_buypasswordforum' => 'forum/item_passwordforum.php',
									'item_card' => 'other/item_postcard.php',
									'item_unusable' => '/item_test.php',
								);
	var $SETTING_CONVERT = array(
									'store_on' => 'market_on',
									'store_guest' => 'market_guests',
									'store_name' => 'market_name',
									'currency_name' => 'market_currency',
									'pointsper_topic' => 'market_post_reply',
									'pointsper_reply' => 'market_post_topic',
									'inventory_max' => 'market_inventory_max',
									'show_inventory' => 'market_show_inventory',
								);
	var $SETTING_DEFAULT = array(
									'market_members_field' => '',
									'market_prefix' => '{blank}',
									'market_suffix' => '',
									'market_register' => '',
									'market_global_tax' => '',
									'market_resell_tax' => '',
									'market_show_money' => '',
								);
	
	function has_mod_installed()
	{
		return $this->ipsclass->DB->field_exists('id','store_shopstock');
	}
	
	function home_page()
	{
		$html = array();
		
		$i++;
		$html[$i] .= $this->ipsclass->adskin->start_form( array(
														 	  	 1 => array( 'section'   , 'components'  ),
																 2 => array( 'act'       , 'market'      ),
																 3 => array( 'code'      , 'convert'     ),
																 4 => array( 'do'        , 'convert'     ),
																 5 => array( 'other'     , 'ibstore'     ),
																 6 => array( 'covert'    , 'item'        ),
														)		);
		$html[$i] .= $this->ipsclass->adskin->start_table("ibStore to ibMarket Item converter");
		$html[$i] .= $this->ipsclass->adskin->add_td_row(array($this->ipsclass->adskin->form_checkbox("empty_store")."Empty categories and items and inventory items stored in ibStore when done"));
		$html[$i] .= $this->ipsclass->adskin->add_td_row(array("Default category: ".$this->ipsclass->adskin->form_dropdown("default_cat", $this->ipsclass->market_admin->build_categories_dropdown())));
		$html[$i] .= $this->ipsclass->adskin->end_form("Convert ibStore categories and items and inventory items to ibMarket categories and items");
		$html[$i] .= $this->ipsclass->adskin->end_table();
		
		$i++;
		$html[$i] .= $this->ipsclass->adskin->start_table("ibStore to ibMarket Settings conveter");
		$html[$i] .= $this->ipsclass->adskin->add_td_row(array("<center>".$this->ipsclass->adskin->js_make_button("Convert ibStore settings to ibMarket settings",$this->ipsclass->base_url."&".$this->ipsclass->form_code_js."&code=convert&do=convert&other=ibstore&covert=settings")."</center>"));
		$html[$i] .= $this->ipsclass->adskin->end_table();
		
		/*$i++;
		$html[$i] .= $this->ipsclass->adskin->start_table("ibStore to ibMarket Logs");
		$html[$i] .= $this->ipsclass->adskin->add_td_row(array("<center>".$this->ipsclass->adskin->js_make_button("Convert ibStore logs to ibMarket logs",$this->ipsclass->base_url."&".$this->ipsclass->form_code_js."&code=convert&do=convert&other=ibstore&covert=logs")."</center>"));
		$html[$i] .= $this->ipsclass->adskin->end_table();*/
		
		if($this->ipsclass->market_class->count_plugin_filename("bank.php") && $this->ipsclass->vars['bank_on'])
		{
			$i++;
			$html[$i] .= $this->ipsclass->adskin->start_form( array(
															 	  	 1 => array( 'section'   , 'components'  ),
																	 2 => array( 'act'       , 'market'      ),
																	 3 => array( 'code'      , 'convert'     ),
																	 4 => array( 'do'        , 'convert'     ),
																	 5 => array( 'other'     , 'ibstore'     ),
																	 6 => array( 'covert'    , 'bank'        ),
															)		);
			$html[$i] .= $this->ipsclass->adskin->start_table("ibStore bank money to ibMarket bank accounts");
			$html[$i] .= $this->ipsclass->adskin->add_td_row(array("Nmae for the Bank Accounts: ".$this->ipsclass->adskin->form_input("account_name","IBStore Bank Account")));
			$html[$i] .= $this->ipsclass->adskin->add_td_row(array($this->ipsclass->adskin->form_checkbox("empty_bank")."Empty all ibStore Bank accounts afterwards"));
			$html[$i] .= $this->ipsclass->adskin->end_form("Convert ibStore Bank Money to ibMarket Bank Accounts");
			$html[$i] .= $this->ipsclass->adskin->end_table();
		}
		
		if($this->ipsclass->market_class->count_plugin_filename("quiz.php"))
		{
			$i++;
			$html[$i] .= $this->ipsclass->adskin->start_form( array(
															 	  	 1 => array( 'section'   , 'components'  ),
																	 2 => array( 'act'       , 'market'      ),
																	 3 => array( 'code'      , 'convert'     ),
																	 4 => array( 'do'        , 'convert'     ),
																	 5 => array( 'other'     , 'ibstore'     ),
																	 6 => array( 'covert'    , 'quiz'        ),
															)		);
			$html[$i] .= $this->ipsclass->adskin->start_table("ibStore quizzes to ibMarket quiz");
			$html[$i] .= $this->ipsclass->adskin->add_td_row(array($this->ipsclass->adskin->form_checkbox("empty_quiz")."Delete all ibStore quizzes afterwards"));
			$html[$i] .= $this->ipsclass->adskin->end_form("Convert ibStore Quizzes to ibMarket Quizzes");
			$html[$i] .= $this->ipsclass->adskin->end_table();
		}
		
		$i++;
		$html[$i] .= $this->ipsclass->adskin->start_table("ibStore Uninstaller");
		$html[$i] .= $this->ipsclass->adskin->add_td_row(array("This will only remove all the ibStore SQL information. You have to manuelly remove the file edits yourself."));
		$html[$i] .= $this->ipsclass->adskin->add_td_row(array("<center>".$this->ipsclass->adskin->js_make_button("Uninstall ibStore",$this->ipsclass->base_url."&".$this->ipsclass->form_code_js."&code=convert&do=convert&other=ibstore&covert=uninstall")."</center>"));
		$html[$i] .= $this->ipsclass->adskin->end_table();
		
		return $html;
	}
	
	function convert()
	{
		$redirect = array(
							'item' => 'item',
							'settings' => 'settings',
							'quiz' => 'quiz',
							'bank' => 'bank',
							'uninstall' => 'uninstall',
						);
		
		if(!isset($redirect[$this->ipsclass->input['covert']]))
		{
			$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=convert","...");
		}
		
		$func = 'convert_'.$redirect[$this->ipsclass->input['covert']];
		$this->$func();
	}
	
	function convert_item()
	{
		$this->ipsclass->input['st'] = intval($this->ipsclass->input['st']);
		$work = array(
						'categories',
						'items',
						'inventory'
					);
		
		if(!in_array($this->ipsclass->input['work'],$work))
		{
			$this->ipsclass->input['work'] = 'categories';
		}
		$func = 'convert_'.$this->ipsclass->input['work'];
		$this->$func();
	}
	
	function convert_categories()
	{
		if($this->ipsclass->input['st'] == 0)
		{
			$this->ipsclass->DB->load_cache_file(ROOT_PATH.'sources/market/install/'.$this->ipsclass->vars['sql_driver'].'_database_queries.php','sql_database_queries');
			
			$this->ipsclass->DB->build_query_from_cache('table_market_temp_convert',array(),'sql_database_queries');
			$this->ipsclass->DB->exec_query();
			
			$this->ipsclass->DB->do_insert('market_temp_convert',array(
																			'c_type' => 'ibstore_cats',
																			'the_data' => serialize(array()),
											)							);
		}
		
		$cats_data = $this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'market_temp_convert','where'=>"c_type='ibstore_cats'"));
		$cat_convert = unserialize($cats_data['the_data']);
		if(!is_array($cat_convert))
		{
			$cat_convert = array();
		}
		
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'store_categories','limit'=>array($this->ipsclass->input['st'],$this->convert_LIMIT)));
		$q = $this->ipsclass->DB->exec_query();
		
		if($this->ipsclass->DB->get_num_rows() == 0)
		{
			$this->ipsclass->market_class->cache_categories();
			if($this->ipsclass->input['empty_store'])
			{
				$this->ipsclass->DB->build_and_exec_query(array('delete'=>'store_categories'));
			}
			
			$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=convert&do=convert&other=ibstore&covert=item&work=items&empty_store=".$this->ipsclass->input['empty_store']."&default_cat=".$this->ipsclass->input['default_cat'],"Converted Categories...");
		}
		
		while($cat = $this->ipsclass->DB->fetch_row($q))
		{
			$this->ipsclass->DB->do_insert('market_categories',array(
																		'cat_parent_id' => -1,
																		'cat_icon' => 'blank.gif',
																		'cat_name' => $cat['cat_name'],
																		'cat_description' => $cat['cat_desc'],
																		'price_multiplier' => 1,
																		'cat_tax' => 0,
											)						);
			$cat_convert[$cat['catid']] = $this->ipsclass->DB->get_insert_id();
		}
		
		$this->ipsclass->DB->do_update('market_temp_convert',array(
																		'the_data' => serialize($cat_convert),
										),"c_type='ibstore_cats'");
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=convert&do=convert&other=ibstore&covert=item&work=categories&st=".($this->ipsclass->input['st']+$this->convert_LIMIT)."&empty_store=".$this->ipsclass->input['empty_store']."&default_cat=".$this->ipsclass->input['default_cat'],"Converting Categories...");
	}
	
	function convert_items()
	{
		if($this->ipsclass->input['st'] == 0)
		{
			$this->ipsclass->DB->do_insert('market_temp_convert',array(
																			'c_type' => 'ibstore_item',
																			'the_data' => serialize(array()),
											)							);
		}
		
		$cats_data = $this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'market_temp_convert','where'=>"c_type='ibstore_cats'"));
		$cat_convert = unserialize($cats_data['the_data']);
		$cat_convert[0] = $this->ipsclass->input['default_cat'];
		
		$item_data = $this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'market_temp_convert','where'=>"c_type='ibstore_item'"));
		$item_convert = unserialize($item_data['the_data']);
		if(!is_array($item_convert))
		{
			$item_convert = array();
		}
		$units = array( 'm' => 60, 'h' => 3600, 'd' => 86400, 'w' => 604800 );
		
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'store_shopstock','limit'=>array($this->ipsclass->input['st'],$this->convert_LIMIT)));
		$q = $this->ipsclass->DB->exec_query();
		
		if($this->ipsclass->DB->get_num_rows() == 0)
		{
			// Convert the fields now
			if($this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'store_shopstock','where'=>"module='ownchange/item_addtopost'")))
			{
				if($this->ipsclass->DB->field_exists("post_addon", "members"))
				{
					$this->ipsclass->DB->build_and_exec_query(array('update'=>'members','set'=>"posts_added=post_addon"));
				}
			}
			if($this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'store_shopstock','where'=>"module='ownchange/item_nameeffect'")))
			{
				if($this->ipsclass->DB->field_exists("name_prefix", "members") && $this->ipsclass->DB->field_exists("name_suffix", "members"))
				{
					$this->ipsclass->DB->build_and_exec_query(array('update'=>'members','set'=>"effect_prefix=name_prefix,effect_suffix=name_suffix"));
				}
			}
			
			// Convert random item
			$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'store_shopstock','where'=>"module='ownpoints/item_mysterybox' OR module='ownpoints/item_mysterything'"));
			$q = $this->ipsclass->DB->exec_query();
			while($item = $this->ipsclass->DB->fetch_row($q))
			{
				$new_item = $this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'market_items','where'=>"item_id=".$item_convert[$item['id']]));
				$settings = unserialize($new_item['item_config']);
				$old_ids = unserialize($item['settings']);
				$settings['items'] = array();
				foreach(explode("|",$old_ids['giveitems'][0]) as $old_item_id)
				{
					$settings['items'][] = $item_convert[$old_item_id];
				}
				$this->ipsclass->DB->do_update('market_items',array('item_config'=>serialize($settings)),"item_id=".$item_convert[$item['id']]);
			}
			
			// Update transfer settings
			$item_ids = array();
			$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'store_shopstock','where'=>"can_trade=1"));
			$this->ipsclass->DB->exec_query();
			while($item = $this->ipsclass->DB->fetch_row())
			{
				$item_ids[] = $item_convert[$item['id']];
			}
			if(is_array($this->ipsclass->cache['market_plugin']) && count($this->ipsclass->cache['market_plugin']))
			{
				foreach($this->ipsclass->cache['market_plugin'] as $plugin)
				{
					if($plugin['filename'] == "transfer.php")
					{
						$settings = unserialize($plugin['plugin_config']);
						$settings['allow_items'] = array_merge($settings['allow_items'],$item_ids);
						$this->ipsclass->DB->do_update('market_plugins',array(
																				'plugin_config' => serialize($settings),
											),"link='".$plugin['link']."'");
					}
				}
			}
			
			$this->ipsclass->market_class->cache_items();
			if($this->ipsclass->input['empty_store'])
			{
				$this->ipsclass->DB->build_and_exec_query(array('delete'=>'store_shopstock'));
			}
			
			$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=convert&do=convert&other=ibstore&covert=item&work=inventory&empty_store=".$this->ipsclass->input['empty_store']."&default_cat=".$this->ipsclass->input['default_cat'],"Converted Items...");
		}
		
		while($s_item = $this->ipsclass->DB->fetch_row($q))
		{
			if(!$this->FILENAME_CONVERT[$s_item['module']])
			{
				continue;
			}
			
			$item = array(
							'filename' => $this->FILENAME_CONVERT[$s_item['module']],
							'item_name' => $s_item['item_name'],
							'item_description' => $s_item['item_desc'],
							'category' => $cat_convert[$s_item['category']],
							'icon' => $s_item['icon'],
							'hide_item' => $s_item['is_hidden'],
							'base_price' => $s_item['sell_price'],
							'base_resell' => $s_item['can_resell'] ? $this->ipsclass->numbers->multiply($this->ipsclass->vars['resell_percentage'],$s_item['sell_price']) : 0,
							'tax' => 0,
							'stock' => $s_item['stock'],
							'allow_resell' => intval($s_item['can_resell'] | $s_item['can_delete']),
							'resell_putback' => 1,
							'restock' => 0,
							'restock_when' => 0,
							'restock_minute' => 0,
							'restock_hour' => 0,
							'restock_day' => 0,
							'restock_howmuch' => 0,
							'restock_time' => 0,
							'inventory_limit' => $s_item['item_limit'],
							'item_config' => '',
						);
			
			if($item['stock'] != -1 && $s_item['restock_amount'] != 0)
			{
				$r_time = explode("_" ,$s_item['restock_time']);
				$item['restock'] = 1;
				$item['restock_when'] = min($s_item['restock_at'],$s_item['restock_untill']);
				$item['restock_howmuch'] = $s_item['restock_amount'];
				$total_time = $r_time[0] * $units[$r_time[1]];
				$total_time = min($total_time,694740);
				if($total_time >= 86400)
				{
					$item['restock_day'] = min(floor($total_time/86400),7);
					$total_time = $total_time - $item['restock_day'] * 86400;
				}
				if($total_time >= 3600)
				{
					$item['restock_hour'] = floor($total_time/3600);
					$total_time = $total_time % 3600;
				}
				if($total_time >= 60)
				{
					$item['restock_minute'] = floor($total_time/60);
					$total_time = $total_time % 60;
				}
				
				$this->ipsclass->cache['market_items'][-1] = $item;
				$item['restock_time'] = $this->ipsclass->market_class->next_restock_time(-1);
			}
			
			$this->ipsclass->market_class->load_item(array_merge(array('item_id'=>-1),$item));
			if(!$this->ipsclass->market_class->items_loaded[-1]->allow_multiple and $this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'market_items','where'=>"filename='".$item['filename']."'")))
			{
				continue;
			}
			
			$setting = unserialize($s_item['settings']);
			$input = array();
			$input['protected'] = $s_item['protect_groups'] == 'none' ? array() : explode("|",$s_item['protect_groups']);
			if($s_item['module'] == 'bank/item_increaseinterest')
			{
				$input['rate'] = $setting['add'][0];
				$input['max_rate'] = $setting['max'][0];
			}
			elseif($s_item['module'] == 'otherusers/item_decreaseothereinterest')
			{
				$input['rate'] = $setting['decrease'][0];
				$input['min_rate'] = 0;
			}
			elseif($s_item['module'] == 'otherusers/item_temporaryban')
			{
				$input['max_day'] = $setting['max'][0];
			}
			elseif($s_item['module'] == 'otherusers/item_uploadotheresavatar')
			{
				$input['upload'] = 1;
			}
			elseif($s_item['module'] == 'ownchange/item_addtopost')
			{
				$input['add_post'] = $setting['post'][0];
			}
			elseif($s_item['module'] == 'ownchange/item_changegroup')
			{
				$input['group_id'] = $setting['group'][0];
			}
			elseif($s_item['module'] == 'ownchange/item_nameeffect')
			{
				$trans = array(
									1 => 'italics',
									2 => 'dropshadow',
									3 => 'shadow',
									4 => 'blur',
									5 => 'glow',
									6 => 'remove',
								);
				$input['effect'] = $trans[$setting['effect'][0]];
			}
			elseif($s_item['module'] == 'ownchange/item_messagetouser')
			{
				$input['title'] = "Message";
				$input['message'] = $setting['message'][0];
				$input['destination'] = $setting['messagetype'][0] ? 'screen' : 'pm';
			}
			elseif($s_item['module'] == 'ownpoints/item_mysterybox')
			{
				$input['items'] = array();
				$input['deduct'] = 0;
			}
			elseif($s_item['module'] == 'ownpoints/item_mysterything')
			{
				$input['percent'] = 50;
				$input['lowest'] = $setting['lowest'][0];
				$input['highest'] = $setting['highest'][0];
				$input['items'] = array();
				$input['deduct'] = 0;
			}
			elseif($s_item['module'] == 'ownpoints/item_randommoney')
			{
				$input['lowest'] = $setting['lowest'][0];
				$input['highest'] = $setting['highest'][0];
			}
			elseif($s_item['module'] == 'steal/item_basicsteal')
			{
				$input['amount_min'] = $setting['min_steal'][0];
				$input['amount_max'] = $setting['max_steal'][0];
				$input['percent_min'] = $setting['percent'][0];
				$input['percent_max'] = $setting['percent'][0];
			}
			elseif($s_item['module'] == 'topic/item_closeopenowntopic')
			{
				$input['no_forum'] = explode("|",$setting['badforums'][0]);
				$input['limit'] = 1;
			}
			elseif($s_item['module'] == 'topic/item_opencloseanytopic')
			{
				$input['no_forum'] = explode("|",$setting['badforums'][0]);
				$input['limit'] = 0;
			}
			elseif($s_item['module'] == 'topic/item_pinunpinanytopic')
			{
				$input['no_forum'] = explode("|",$setting['badforums'][0]);
				$input['limit'] = 0;
			}
			elseif($s_item['module'] == 'topic/item_pinunpinowntopic')
			{
				$input['no_forum'] = explode("|",$setting['badforums'][0]);
				$input['limit'] = 1;
			}
			elseif($s_item['module'] == 'upload/item_uploademoticon')
			{
				$input['overwrite'] = 0;
			}
			elseif($s_item['module'] == 'item_buypasswordforum')
			{
				$input['forum'] = $setting['password'][0];
			}
			elseif($s_item['module'] == 'item_card')
			{
				$input['obey_pm'] = 0;
				$input['message'] = $this->ipsclass->parser->pre_edit_parse($setting['cardtext'][0])."\n{extra_msg}";
			}
			
			$this->ipsclass->market_class->items_loaded[-1]->admin_save($item,$input);
			
			$this->ipsclass->DB->do_insert('market_items',$item);
			$item_convert[$s_item['id']] = $this->ipsclass->DB->get_insert_id();
			
			unset($this->ipsclass->market_class->items_loaded[-1]);
		}
		
		$this->ipsclass->DB->do_update('market_temp_convert',array(
																		'the_data' => serialize($item_convert),
										),"c_type='ibstore_item'");
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=convert&do=convert&other=ibstore&covert=item&work=items&st=".($this->ipsclass->input['st']+$this->convert_LIMIT)."&empty_store=".$this->ipsclass->input['empty_store']."&default_cat=".$this->ipsclass->input['default_cat'],"Converting items...");
	}
	
	function convert_inventory()
	{
		$item_data = $this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'market_temp_convert','where'=>"c_type='ibstore_item'"));
		$item_convert = unserialize($item_data['the_data']);
		
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'store_inventory','limit'=>array($this->ipsclass->input['st'],$this->convert_LIMIT)));
		$q = $this->ipsclass->DB->exec_query();
		
		if($this->ipsclass->DB->get_num_rows() == 0)
		{
			if($this->ipsclass->input['empty_store'])
			{
				$this->ipsclass->DB->build_and_exec_query(array('delete'=>'store_inventory'));
			}
			
			$this->ipsclass->DB->sql_drop_table('market_temp_convert');
			
			$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=convert","Finished converting...");
		}
		
		while($old_inv = $this->ipsclass->DB->fetch_row($q))
		{
			$inv_item = array(
								'member_id' => $old_inv['owner_id'],
								'item' => $item_convert[$old_inv['item_id']],
								'price_bought' => $old_inv['price_paid'],
								'resell_price' => $this->ipsclass->cache['market_items'][$item_convert[$old_inv['item_id']]]['resell'],
								'time_bought' => time(),
							);
			if($item_convert[$old_inv['item_id']] && $this->ipsclass->market_class->items_loaded[$item_convert[$old_inv['item_id']]]->public_on_create_item($inv_item))
			{
				$this->ipsclass->DB->do_insert('market_inventory',$inv_item);
			}
		}
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=convert&do=convert&other=ibstore&covert=item&work=inventory&st=".($this->ipsclass->input['st']+$this->convert_LIMIT)."&empty_store=".$this->ipsclass->input['empty_store']."&default_cat=".$this->ipsclass->input['default_cat'],"Converting Inventory Items...");
	}
	
	function convert_settings()
	{
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'groups'));
		$g = $this->ipsclass->DB->exec_query();
		while($group = $this->ipsclass->DB->fetch_row($g))
		{
			$this->ipsclass->DB->do_update('groups',array(
															'g_market_view' => $group['g_access_store'],
															'g_market_use' => $group['g_buyitems'],
															'g_market_discount' => $group['g_discount'],
								),"g_id=".$group['g_id']);
		}
		
		foreach($this->SETTING_CONVERT as $old_key => $new_key)
		{
			$this->ipsclass->DB->do_update('conf_settings',array(
																	'conf_value' => $this->ipsclass->vars[$old_key],
									),"conf_key='".$new_key."'");
		}
		
		$this->SETTING_DEFAULT['market_suffix'] = " ".$this->ipsclass->vars['currency_name'];
		foreach($this->SETTING_DEFAULT as $key => $default)
		{
			$this->ipsclass->DB->do_update('conf_settings',array(
																	'conf_value' => $default,
										),"conf_key='".$key."'");
		}
		
		$this->ipsclass->DB->do_update('components',array('com_url_title'=>$this->ipsclass->vars['store_name']),"com_section='market'");
		
		require_once( ROOT_PATH.'sources/action_admin/components.php' );
		$components           = new ad_components();
		$components->ipsclass =& $this->ipsclass;
		$components->components_rebuildcache();
		
		require_once( ROOT_PATH.'sources/action_admin/settings.php' );
		$settings           = new ad_settings();
		$settings->ipsclass =& $this->ipsclass;
		$settings->setting_rebuildcache();
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=convert","Finished converting settings...");
	}
	
	function convert_bank()
	{
		if(!$this->ipsclass->input['account_name'])
		{
			$this->ipsclass->admin->error("You need to specify a valid account name");
		}
		
		$this->ipsclass->input['st'] = intval($this->ipsclass->input['st']);
		
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'members','where'=>"deposited != 0",'limit'=>array($this->ipsclass->input['st'],$this->convert_LIMIT)));
		$q = $this->ipsclass->DB->exec_query();
		
		if($this->ipsclass->DB->get_num_rows() == 0)
		{
			if($this->ipsclass->input['empty_bank'])
			{
				$this->ipsclass->DB->do_update('members',array('deposited'=>0,'last_collect'=>'','extra_interest'=>0));
			}
			
			$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=convert","Finished converting...");
		}
		
		while($member = $this->ipsclass->DB->fetch_row($q))
		{
			$this->ipsclass->DB->do_insert('market_bank_accounts',array(
																			'a_random' => $this->ipsclass->numbers->multiply(1000000,(float)microtime()),
																			'a_mem_id' => $member['id'],
																			'a_name' => $this->ipsclass->input['account_name'],
																			'a_open' => $member['joined'],
																			'balance' => $member['deposited'],
																			'a_interest_time' => 86400,
																			'a_last_interest' => strtotime($member['last_collect']),
																			'interest_rate' => $this->ipsclass->numbers->add($this->ipsclass->vars['base_interest'],$member['extra_interest']),
																			'a_deposit_fee' => $this->ipsclass->vars['bank_deposite'],
																			'a_withdraw_fee' => $this->ipsclass->vars['bank_withdraw'],
																			'a_delete_fee' => 0,
											)							);
		}
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=convert&do=convert&other=ibstore&covert=bank&st=".($this->ipsclass->input['st']+$this->convert_LIMIT)."&empty_bank=".$this->ipsclass->input['empty_bank']."&account_name=".$this->ipsclass->input['account_name'],"Converting Bank money...");
	}
	
	function convert_quiz()
	{
		$this->ipsclass->input['st'] = intval($this->ipsclass->input['st']);
		$work = array(
						'quizzes',
						'question',
						'played'
					);
		
		if(!in_array($this->ipsclass->input['work'],$work))
		{
			$this->ipsclass->input['work'] = 'quizzes';
		}
		$func = 'convert_'.$this->ipsclass->input['work'];
		$this->$func();
	}
	
	function convert_quizzes()
	{
		if($this->ipsclass->input['st'] == 0)
		{
			$this->ipsclass->DB->load_cache_file(ROOT_PATH.'sources/market/install/'.$this->ipsclass->vars['sql_driver'].'_database_queries.php','sql_database_queries');
			
			$this->ipsclass->DB->build_query_from_cache('table_market_temp_convert',array(),'sql_database_queries');
			$this->ipsclass->DB->exec_query();
			
			$this->ipsclass->DB->do_insert('market_temp_convert',array(
																			'c_type' => 'ibstore_quizzes',
																			'the_data' => serialize(array()),
											)							);
		}
		
		$quiz_data = $this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'market_temp_convert','where'=>"c_type='ibstore_quizzes'"));
		$quiz_convert = unserialize($quiz_data['the_data']);
		
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'store_quizinfo','limit'=>array($this->ipsclass->input['st'],$this->convert_LIMIT)));
		$q = $this->ipsclass->DB->exec_query();
		
		if($this->ipsclass->DB->get_num_rows() == 0)
		{
			if($this->ipsclass->input['empty_quiz'])
			{
				$this->ipsclass->DB->build_and_exec_query(array('delete'=>'store_quizinfo'));
			}
			
			$this->ipsclass->cache['ibm_quizzes'] = array();
			
			$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'market_quizzes'));
			$this->ipsclass->DB->exec_query();
			while($quiz = $this->ipsclass->DB->fetch_row())
			{
				$quiz['q_prize_items'] = unserialize($quiz['q_prize_items']);
				$this->ipsclass->cache['ibm_quizzes'][$quiz['quiz_id']] = $quiz;
			}
			
			$this->ipsclass->update_cache( array( 'name' => 'ibm_quizzes', 'array' => 1, 'deletefirst' => 1 ) );
			
			$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=convert&do=convert&other=ibstore&covert=quiz&work=question&empty_quiz=".$this->ipsclass->input['empty_quiz'],"Converted Quizzes...");
		}
		
		while($quiz = $this->ipsclass->DB->fetch_row($q))
		{
			$this->ipsclass->DB->do_insert('market_quizzes',array(
																	'q_name' => $quiz['quizname'],
																	'q_description' => $quiz['quizdesc'],
																	'q_tries' => 1,
																	'q_percent_win' => $quiz['percent_needed'],
																	'q_ending_time' => $quiz['started_on'] + $quiz['run_for'] * 86400,
																	'q_timeout' => $quiz['timeout'] / 60,
																	'q_prize_money' => $quiz['amount_won'],
																	'q_prize_items' => serialize(array()),
											)					);
			$quiz_convert[$quiz['q_id']] = $this->ipsclass->DB->get_insert_id();
		}
		
		$this->ipsclass->DB->do_update('market_temp_convert',array(
																		'the_data' => serialize($quiz_convert),
										),"c_type='ibstore_item'");
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=convert&do=convert&other=ibstore&covert=quiz&work=quizzes&st=".($this->ipsclass->input['st']+$this->convert_LIMIT)."&empty_quiz=".$this->ipsclass->input['empty_quiz'],"Converting Quizzes...");
	}
	
	function convert_question()
	{
		$quiz_data = $this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'market_temp_convert','where'=>"c_type='ibstore_quizzes'"));
		$quiz_convert = unserialize($quiz_data['the_data']);
		
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'store_quizs','limit'=>array($this->ipsclass->input['st'],$this->convert_LIMIT)));
		$q = $this->ipsclass->DB->exec_query();
		
		if($this->ipsclass->DB->get_num_rows() == 0)
		{
			if($this->ipsclass->input['empty_quiz'])
			{
				$this->ipsclass->DB->build_and_exec_query(array('delete'=>'store_quizs'));
			}
			
			$this->ipsclass->cache['ibm_quiz_question'] = array();
			
			$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'market_quiz_question'));
			$this->ipsclass->DB->exec_query();
			while($question = $this->ipsclass->DB->fetch_row())
			{
				$question['choices'] = unserialize($question['choices']);
				$question['answer'] = unserialize($question['answer']);
				$this->ipsclass->cache['ibm_quiz_question'][$question['quiz_id']][$question['question_id']] = $question;
			}
			
			$this->ipsclass->update_cache( array( 'name' => 'ibm_quiz_question', 'array' => 1, 'deletefirst' => 1 ) );
			
			$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=convert&do=convert&other=ibstore&covert=quiz&work=played&empty_quiz=".$this->ipsclass->input['empty_quiz'],"Converted Quiz Questions...");
		}
		
		while($question = $this->ipsclass->DB->fetch_row($q))
		{
			$type = '';
			$choices = array();
			$answer = array();
			if($question['type'] == 'dropdown')
			{
				$match = array();
				$type = 'smultiple';
				foreach(explode("||",$question['anwser']) as $a)
				{
					if(preg_match("#{answer.+?_(.+?):(.+)}#is",$a,$match))
					{
						$choices[] = $match[2];
						if($match[1] == 1)
						{
							$answer[] = count($choices) - 1;
						}
					}
				}
			}
			elseif($question['type'] == 'multiq')
			{
				$type = 'single';
				foreach(explode("||",$question['anwser']) as $a)
				{
					if(preg_match("#{answer.+?_(.+?):(.+)}#is",$a,$match))
					{
						$answer[] = $match[2];
					}
				}
			}
			elseif($question['type'] == 'single')
			{
				$type = 'single';
				$answer[] = $question['anwser'];
			}
			$this->ipsclass->DB->do_insert('market_quiz_question',array(
																			'quiz_id' => $quiz_convert[$question['quiz_id']],
																			'q_type' => $type,
																			'question' => $question['question'],
																			'choices' => serialize($choices),
																			'answer' => serialize($answer),
																			'case_sensitive' => 0,
																			'space_sensitive' => 0,
																			'weight' => 1,
																			'penalty' => 0,
																			'blank_penalty' => 0,
																			'match_choice' => 1,
											)							);
		}
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=convert&do=convert&other=ibstore&covert=quiz&work=question&st=".($this->ipsclass->input['st']+$this->convert_LIMIT)."&empty_quiz=".$this->ipsclass->input['empty_quiz'],"Converting Quiz Questions...");
	}
	
	function convert_played()
	{
		$quiz_data = $this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'market_temp_convert','where'=>"c_type='ibstore_quizzes'"));
		$quiz_convert = unserialize($quiz_data['the_data']);
		
		$this->ipsclass->init_load_cache(array('ibm_quizzes','ibm_quiz_question'));
		
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'store_quizwinners','limit'=>array($this->ipsclass->input['st'],$this->convert_LIMIT)));
		$q = $this->ipsclass->DB->exec_query();
		
		if($this->ipsclass->DB->get_num_rows() == 0)
		{
			if($this->ipsclass->input['empty_quiz'])
			{
				$this->ipsclass->DB->build_and_exec_query(array('delete'=>'store_quizwinners'));
			}
			
			$this->ipsclass->DB->sql_drop_table('market_temp_convert');
			
			$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=convert","Finished Converting...");
		}
		
		while($player = $this->ipsclass->DB->fetch_row($q))
		{
			$this->ipsclass->DB->do_insert('market_quiz_taken',array(
																		'quiz_id' => $quiz_convert[$player['quiz_id']],
																		'member_id' => $player['member_id'],
																		'ip_address' => '',
																		'time_start' => time(),
																		'time_taken' => time()+$player['time_took']*60,
																		'percent_correct' => $player['amount_right']/count($this->ipsclass->cache['ibm_quiz_question'][$quiz_convert[$player['quiz_id']]]),
																		'passed_quiz' => $player['amount_right']/count($this->ipsclass->cache['ibm_quiz_question'][$quiz_convert[$player['quiz_id']]])*100 >= $this->ipsclass->cache['ibm_quizzes'][$quiz_convert[$player['quiz_id']]]['q_percent_win'] ? 1 : 0,
											)						);
		}
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=convert&do=convert&other=ibstore&covert=quiz&work=question&st=".($this->ipsclass->input['st']+$this->convert_LIMIT)."&empty_quiz=".$this->ipsclass->input['empty_quiz'],"Converting Quiz Players...");
	}
	
	function convert_uninstall()
	{
		$this->ipsclass->DB->sql_drop_table( 'store_categories'  );
		$this->ipsclass->DB->sql_drop_table( 'store_creditcards' );
		$this->ipsclass->DB->sql_drop_table( 'store_inventory'   );
		$this->ipsclass->DB->sql_drop_table( 'store_logs'        );
		$this->ipsclass->DB->sql_drop_table( 'store_modlogs'     );
		$this->ipsclass->DB->sql_drop_table( 'store_quizinfo'    );
		$this->ipsclass->DB->sql_drop_table( 'store_quizs'       );
		$this->ipsclass->DB->sql_drop_table( 'store_quizwinners' );
		$this->ipsclass->DB->sql_drop_table( 'store_shopstock'   );
		
		if($this->ipsclass->DB->field_exists("g_fine_edit",           "groups")) $this->ipsclass->DB->sql_drop_field('groups','g_fine_edit'          );
		if($this->ipsclass->DB->field_exists("g_allow_inventoryedit", "groups")) $this->ipsclass->DB->sql_drop_field('groups','g_allow_inventoryedit');
		if($this->ipsclass->DB->field_exists("g_discount",            "groups")) $this->ipsclass->DB->sql_drop_field('groups','g_discount'           );
		if($this->ipsclass->DB->field_exists("g_access_store",        "groups")) $this->ipsclass->DB->sql_drop_field('groups','g_access_store'       );
		if($this->ipsclass->DB->field_exists("g_donate_points",       "groups")) $this->ipsclass->DB->sql_drop_field('groups','g_donate_points'      );
		if($this->ipsclass->DB->field_exists("g_donate_items",        "groups")) $this->ipsclass->DB->sql_drop_field('groups','g_donate_items'       );
		if($this->ipsclass->DB->field_exists("g_buyitems",            "groups")) $this->ipsclass->DB->sql_drop_field('groups','g_buyitems'           );
		if($this->ipsclass->DB->field_exists("g_gain_points",         "groups")) $this->ipsclass->DB->sql_drop_field('groups','g_gain_points'        );
		
		if($this->ipsclass->DB->field_exists("deposited",      "members")) $this->ipsclass->DB->sql_drop_field('members','deposited'     );
		if($this->ipsclass->DB->field_exists("auto_collect",   "members")) $this->ipsclass->DB->sql_drop_field('members','auto_collect'  );
		if($this->ipsclass->DB->field_exists("last_collect",   "members")) $this->ipsclass->DB->sql_drop_field('members','last_collect'  );
		if($this->ipsclass->DB->field_exists("extra_interest", "members")) $this->ipsclass->DB->sql_drop_field('members','extra_interest');
		if($this->ipsclass->DB->field_exists("creditcard",     "members")) $this->ipsclass->DB->sql_drop_field('members','creditcard'    );
		
		if($conf = $this->ipsclass->DB->build_and_exec_query( array ( 'select' => 'conf_title_id', 'from' => 'conf_settings_titles', 'where' => "conf_title_keyword='storesettings'" ) ))
		{
			$this->ipsclass->DB->build_and_exec_query(array('delete'=>'conf_settings_titles','where'=>"conf_title_id=".$conf['conf_title_id']));
			$this->ipsclass->DB->build_and_exec_query(array('delete'=>'conf_settings','where'=>"conf_group=".$conf['conf_title_id']));
		}
		
		$this->ipsclass->DB->build_and_exec_query(array('delete'=>'skin_templates','where'=>"group_name='skin_store'"));
		$this->ipsclass->DB->build_and_exec_query(array('delete'=>'skin_templates_cache','where'=>"template_group_name='skin_store'"));
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js,"Finished Uninstalling ibStore...");
	}
}
?>